from django.http import JsonResponse
from rest_framework.utils import json

from utils import requests_pro
from rest_framework.views import APIView
from lxml import etree
from utils import orm

orm.orm_standby()
from dal import models


class ReMenRequests(APIView):
    def get(self, request):
        message = {}
        try:

            sessions = requests_pro.session_requests_b()
            url = "https://movie.douban.com/j/search_subjects?type=movie&tag=%E7%83%AD%E9%97%A8&sort=recommend&page_limit=20&page_start=0"
            ret = sessions.get(url=url)
            ret.encoding = "utf-8"
            ret_text = ret.text
            ret_json = json.loads(ret_text)
            data_list = ret_json['subjects']

            for data in data_list:
                print(data['title'])
                if models.Remen.objects.filter(title=data['title']).exists() == False:
                    models.Remen.objects.create(rate=data['rate'], title=data['title'], url=data['url'], src=data['cover'])
                    models.History.objects.create(rate=data['rate'], title=data['title'], url=data['url'], src=data['cover'])

            message['code'] = 200
            message['message'] = "更新成功"
            return JsonResponse(message)
        except Exception as e:
            print(e)
            message['code'] = 444
            message['message'] = "更新失败"
            return JsonResponse(message)
